package com.dale.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dale.common.dto.BlogDto;
import com.dale.entity.Blog;
import com.dale.entity.SimilarBlog;
import com.dale.mapper.BlogMapper;
import com.dale.mapper.SimilarBlogMapper;
import com.dale.service.RoleService;
import com.dale.service.SimilarBlogService;
import com.dale.util.SimFeatureUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Gyt
 * @create 2021-06-17 - 19:10
 */
@Service
public class SimilarBlogImpl extends ServiceImpl<SimilarBlogMapper, SimilarBlog> implements SimilarBlogService {

    @Autowired
    private BlogMapper blogMapper;

    @Autowired
    private SimilarBlogMapper similarBlogMapper;

    /**
     * 比较复杂了哈  这里需要查出所有其他的blog
     * 再一一计算
     */
    @Override
    @Transactional
    public void getSimilarity(Long id) {

        //新增的blog  查询出来的不包括id为id的（新增的）
        List<BlogDto> blogDtos = blogMapper.getIdContentBlogs(id);

        Blog blog = blogMapper.selectById(id);
//        String content = blog.getContent();
        String title = blog.getTitle();
        //然后一一计算相似度并保存
        for (BlogDto blogDto : blogDtos) {
            double sim = SimFeatureUtil.sim(title, blogDto.getTitle());

            if (sim > 0.1) {
                //存入数据库  不只要计算1和2的 还要给2增加上2和1的
                SimilarBlog similarBlog = new SimilarBlog();

                //不只要计算1和2的
                similarBlog.setSource(id);
                similarBlog.setDestination(blogDto.getId());
                similarBlog.setSimilarity(sim);

                similarBlogMapper.insert(similarBlog);

                //还要给2增加上2和1的  源和目标交换一下
                SimilarBlog similarBlog1 = new SimilarBlog();
                similarBlog1.setSource(blogDto.getId());
                similarBlog1.setDestination(id);
                //相似度不变
                similarBlog1.setSimilarity(sim);
                similarBlogMapper.insert(similarBlog1);
            }
        }
    }


    /**
     * 获取前3篇相似度高的文章
     */
    @Override
    public List<Blog> getSimilarBlogs(Long source) {


        List<Blog> similarity = similarBlogMapper.getSimilarBLogs(source);

//        ArrayList<Blog> blogs = new ArrayList<>();
//
//
//        for (SimilarBlog similarBlog : similarity) {
//            Long destination = similarBlog.getDestination();
//            Blog blog = blogMapper.selectById(destin  ation);
//            blogs.add(blog);
//        }

        return similarity;
    }


}
